<template>
  <div>
    <el-row :gutter="15">
      <el-form
        ref="elForm"
        :model="dataForm"
        :rules="dataRule"
        size="small"
        label-width="100px"
        label-position="right"
      >
        <template v-if="!loading && formOperates">
          <el-col :span="12">
            <el-form-item label="会员名称" prop="vipName">
              <el-input
                v-model="dataForm.vipName"
                placeholder="请输入会员名称"
                clearable
                :maxlength="50"
                :style="{ width: '100%' }"
                :disabled="judgeWrite('vipName') || type == 'detail'"
                @input="inputChange"
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="会员简称" prop="shortName">
              <el-input
                v-model="dataForm.shortName"
                placeholder="请输入会员简称"
                clearable
                :maxlength="6"
                :style="{ width: '100%' }"
                :disabled="judgeWrite('shortName') || type == 'detail'"
                @input="inputChange"
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="信用代码" prop="creditCode">
              <el-input
                v-model="dataForm.creditCode"
                placeholder="请输入信用代码"
                clearable
                :maxlength="18"
                :style="{ width: '100%' }"
                :disabled="judgeWrite('creditCode') || type == 'detail'"
                @input="inputChange"
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="行业类型" prop="industryType">
                <el-select
                v-model="dataForm.industryType"
                placeholder="请选择行业类型"
                clearable
                :disabled="judgeWrite('industryType') || type == 'detail'"
                :style="{ width: '100%' }"
              >
                <el-option
                  v-for="(item, index) in industryTypeOptions"
                  :key="index"
                  :label="item.fullName"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属基地" prop="baseManageId">
              <el-select
                v-model="dataForm.baseManageId"
                placeholder="请选择所属基地"
                clearable
                :disabled="judgeWrite('baseManageId') || type == 'detail'"
                :style="{ width: '100%' }"
              >
                <el-option
                  v-for="(item, index) in baseManageListOptions"
                  :key="index"
                  :label="item.baseName"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="法人" prop="legalName">
              <el-input
                v-model="dataForm.legalName"
                placeholder="请输入法人"
                show-word-limit
                :maxlength="20"
                :disabled="judgeWrite('legalName') || type == 'detail'"
                :style="{ width: '100%' }"
                @input="inputChange"
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="法人手机" prop="legalPhoneNum">
              <el-input
                v-model="dataForm.legalPhoneNum"
                placeholder="请输入法人手机"
                clearable
                :maxlength="11"
                show-word-limit
                :disabled="judgeWrite('legalPhoneNum') || type == 'detail'"
                :style="{ width: '100%' }"
                @input="inputChange"
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系人" prop="contactName">
              <el-input
                v-model="dataForm.contactName"
                placeholder="请输入联系人"
                clearable
                :maxlength="20"
                :disabled="judgeWrite('contactName') || type == 'detail'"
                :style="{ width: '100%' }"
                @input="inputChange"
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系人手机" prop="contactPhoneNum">
              <el-input
                v-model="dataForm.contactPhoneNum"
                placeholder="请输入联系人手机"
                clearable
                :maxlength="11"
                show-word-limit
                :disabled="judgeWrite('contactPhoneNum') || type == 'detail'"
                :style="{ width: '100%' }"
                @input="inputChange"
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="省市区域" prop="addressField">
              <JNPF-Address
                v-model="dataForm.addressField"
                placeholder="请选择省市区域"
                clearable
                :level="2"
                :disabled="judgeWrite('addressField') || type == 'detail'"
              >
              </JNPF-Address>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="详细地址" prop="detailAddress">
              <el-input
                v-model="dataForm.detailAddress"
                placeholder="请输入详细地址"
                clearable
                :maxlength="50"
                :disabled="judgeWrite('detailAddress') || type == 'detail'"
                :style="{ width: '100%' }"
                @input="inputChange"
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="注册资金(万)" prop="registeredCapital">
              <el-input-number
                v-model="dataForm.registeredCapital"
                placeholder="数字文本"
                :step="1"
                :min="0"
                :disabled="judgeWrite('registeredCapital') || type == 'detail'"
              >
              </el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="会员邮箱" prop="vipEmail">
              <el-input
                v-model="dataForm.vipEmail"
                placeholder="请输入会员邮箱"
                clearable
                :disabled="judgeWrite('vipEmail') || type == 'detail'"
                :style="{ width: '100%' }"
                @input="inputChange"
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="公司网址" prop="website">
              <el-input
                v-model="dataForm.website"
                placeholder="请输入公司网址"
                clearable
                :maxlength="300"
                :disabled="judgeWrite('website') || type == 'detail'"
                :style="{ width: '100%' }"
                @input="inputChange"
              >
                <template slot="prepend">https://</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="营业执照" prop="businessLicense">
              <JNPF-UploadImg
                v-model="dataForm.businessLicense"
                :fileSize="5"
                sizeUnit="MB"
                :limit="1"
                :disabled="judgeWrite('businessLicense') || type == 'detail'"
              >
              </JNPF-UploadImg>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="会员等级" prop="vipLevelId">
              <el-select
                v-model="dataForm.vipLevelId"
                placeholder="请选择会员等级"
                clearable
                :style="{ width: '100%' }"
                :disabled="judgeWrite('vipLevelId') || type == 'detail'"
              >
                <el-option
                  v-for="(item, index) in vipLevelIdOptions"
                  :key="index"
                  :label="item.levelName"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="会费到期时间" prop="expireTime">
              <el-date-picker
                v-model="dataForm.expireTime"
                placeholder="请选择会费到期时间"
                clearable
                :style="{ width: '100%' }"
                type="date"
                format="yyyy-MM-dd"
                value-format="timestamp"
                :disabled="judgeWrite('expireTime') || type == 'detail'"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </template>
      </el-form>
    </el-row>
    <UserBox v-if="userBoxVisible" ref="userBox" @submit="submit" />
  </div>
</template>
<script>
import { getVipGrade } from '@/api/asso/vip/vipLevel'
import { vipLevelInfo, editVipInfo, addVipInfo, baseManageList, vipLevelList } from '@/api/asso/vip/vipInfo'
import { getToken } from '@/utils/auth'
export default {
  components: {},
  props: [],
  data() {
    return {
      type: '',
      visible: false,
      loading: false,
      setting: {},
      eventType: "",
      userBoxVisible: false,
      currTableConf: {},
      addTableConf: {},
      tableRows: {},
      dataForm: {
        id: "",
        flowId: "",
        status: 1,
        freeapproveruserid: "",
        flowUrgent: 1,
        vipName: undefined,
        shortName: undefined,
        creditCode: undefined,
        industryType: undefined,
        baseManageId: undefined,
        legalName: undefined,
        legalPhoneNum: undefined,
        contactName: undefined,
        contactPhoneNum: undefined,
        addressField: [],
        detailAddress: undefined,
        registeredCapital: undefined,
        vipEmail: undefined,
        website: undefined,
        businessLicense: [],
        vipLevelId: undefined,
        expireTime: undefined
      },
      uploadHeaders: {
        token: getToken()
      },
      tableRequiredData: {},
      dataRule: {
        vipName: [
          {
            required: true,
            message: "请输入会员名称",
            trigger: "blur",
          },
        ],
        shortName: [
          {
            required: true,
            message: "请输入会员简称",
            trigger: "blur",
          },
        ],
        creditCode: [
          {
            required: true,
            message: "请输入社会信用代码",
            trigger: "blur",
          },
        ],
        industryType: [
          {
            required: true,
            message: "请输入行业类型",
            trigger: "blur",
          },
        ],
        legalName: [
          {
            required: true,
            message: "请输入法人",
            trigger: "blur",
          },
        ],
        legalPhoneNum: [
          {
            required: true,
            message: "请输入法人手机号",
            trigger: "blur",
          },
          {
            pattern: /^1[3456789]\d{9}$|^0\d{2,3}-?\d{7,8}$/,
            message: '请输入正确的联系电话',
            trigger: 'blur'
          },
        ],
        contactName: [
          {
            required: true,
            message: "请输入联系人",
            trigger: "blur",
          },
        ],
        contactPhoneNum: [
          {
            required: true,
            message: "请输入手机",
            trigger: "blur",
          },
          {
            pattern: /^1[3456789]\d{9}$|^0\d{2,3}-?\d{7,8}$/,
            message: '请输入正确的联系电话',
            trigger: 'blur'
          },
        ],
        detailAddress: [
          {
            required: true,
            message: "请输入详细地址",
            trigger: "blur",
          },
        ],
        vipLevelId: [
          {
            required: true,
            message: "请选择会员等级",
            trigger: "change",
          },
        ],
        expireTime: [
          {
            required: true,
            message: "请选择到期时间",
            trigger: "change",
          },
        ],
      },
      vipLevelIdOptions: [],
      industryTypeOptions: [],
      baseManageListOptions: []
    };
  },
  computed: {
    formOperates() {
      return this.setting.formOperates
    },
  },
  watch: {},
  created() {},
  mounted() {},
  methods: {
    judgeShow(id) {
      if (!this.setting.formOperates || !this.setting.formOperates.length)
        return true;
      let arr = this.setting.formOperates.filter((o) => o.id === id) || [];
      if (!arr.length) return true;
      let item = arr[0];
      return item.read;
    },
    judgeWrite(id) {
      if (!this.setting.formOperates || !this.setting.formOperates.length)
        return false;
      let arr = this.setting.formOperates.filter((o) => o.id === id) || [];
      if (!arr.length) return true;
      let item = arr[0];
      return !item.write;
    },
    goBack() {
      this.$emit("refresh");
    },
    init(data) {
      this.type = data.stateType
      this.dataForm.id = data.id || "";
      this.setting = data;
      this.visible = true;
      this.getBaseManageList()
      this.getVipGrade()
      this.industryType()
      this.updateDataRule();
      this.$nextTick(() => {
        this.$refs["elForm"].resetFields();
        if (this.dataForm.id) {
          this.loading = true;
            vipLevelInfo(this.dataForm.id).then(res => {
                this.dataInfo(res.data);
                this.loading = false;
            })
        }
        this.$emit("setPageLoad");
      });
      this.$store.commit("generator/UPDATE_RELATION_DATA", {});
    },
    updateDataRule() {
      let newRules = {};
      for (let i = 0; i < this.setting.formOperates.length; i++) {
        const item = this.setting.formOperates[i];
        if (!item.id.includes("-")) {
          const newRulesItem = {
            required: item.required,
            message: item.name + "不能为空",
            trigger: item.trigger || "blur",
          };
          if (!this.dataRule.hasOwnProperty(item.id)) {
            if (item.required) this.$set(newRules, item.id, [newRulesItem]);
          } else {
            let withoutRequiredItem = true;
            for (let i = 0; i < this.dataRule[item.id].length; i++) {
              if (this.dataRule[item.id][i].hasOwnProperty("required")) {
                // this.dataRule[item.id][i].required = item.required;
                withoutRequiredItem = false;
              }
            }
            if (withoutRequiredItem && item.required)
              this.dataRule[item.id].push(newRulesItem);
          }
        } else {
          let key = item.id.split("-")[0];
          let newId = item.id.split("-")[1];
          let newItem = {
            ...item,
            id: newId,
          };
          if (!this.tableRequiredData.hasOwnProperty(key)) {
            this.$set(this.tableRequiredData, key, [newItem]);
          } else {
            this.tableRequiredData[key].push(newItem);
          }
        }
      }
      this.dataRule = { ...this.dataRule, ...newRules };
    },
    exist() {
      let isOk = true;
      for (let key in this.tableRequiredData) {
        if (this.dataForm[key] && Array.isArray(this.dataForm[key])) {
          for (let i = 0; i < this.dataForm[key].length; i++) {
            let item = this.dataForm[key][i];
            inner: for (let id in item) {
              let arr =
                this.tableRequiredData[key].filter((o) => o.id === id) || [];
              if (!arr.length) continue inner;
              if (arr[0].required) {
                let msg = `${arr[0].name}不能为空`;
                let boo = true;
                if (arr[0].dataType === "array") {
                  boo = !this.jnpf.isEmptyArray(item[id]);
                } else {
                  boo = !this.jnpf.isEmpty(item[id]);
                }
                if (!boo) {
                  this.$message({
                    message: msg,
                    type: "error",
                    duration: 1000,
                  });
                  isOk = false;
                  break;
                }
              }
            }
          }
        }
      }
      return isOk;
    },
    judgeRequired(id) {
      if (!this.formOperates || !this.formOperates.length) return false;
      let arr = this.formOperates.filter((o) => o.id === id) || [];
      if (!arr.length) return false;
      let item = arr[0];
      return item.required;
    },
    // 表单提交
    dataFormSubmit(eventType, flowUrgent) {
      this.$refs["elForm"].validate((valid) => {
        if (valid) {
          if (this.exist && !this.exist()) return;
          if (eventType === "audit" || eventType === "reject") {
            this.$emit("eventReceiver", this.dataForm, eventType);
            return;
          }
          this.dataForm.status = eventType === "submit" ? 0 : 1;
          this.dataForm.flowId = this.setting.flowId;
          this.dataForm.flowUrgent = flowUrgent;
          this.eventType = eventType;
          if (this.eventType === "submit") {
            this.$confirm("您确定要提交当前流程吗, 是否继续?", "提示", {
              type: "warning",
            })
              .then(() => {
                this.request();
              })
              .catch(() => {});
          } else {
            this.request();
          }
        }
      });
    },
    request() {
      var _data = this.dataList();
      if (!this.dataForm.id) {
            addVipInfo(_data).then(res => {
                  this.$message({
                    message: res.msg,
                    type: "success",
                    duration: 1000,
                    onClose: () => {
                        this.visible = false;
                        this.$emit("close", true);
                    },
                });
            })
      } else {
            editVipInfo(_data, this.dataForm.id).then(res => {
                  this.$message({
                    message: res.msg,
                    type: "success",
                    duration: 1000,
                    onClose: () => {
                        this.visible = false;
                        this.$emit("close", true);
                    },
                });
            })
      }
    },
    openSelectDialog(key) {
      this.currTableConf = this.addTableConf[key];
      this.currVmodel = key;
      this.selectDialogVisible = true;
      this.$nextTick(() => {
        this.$refs.selectDialog.init();
      });
    },
    addForSelect(data) {
      for (let i = 0; i < data.length; i++) {
        let item = { ...this.tableRows[this.currVmodel], ...data[i] };
        this.dataForm[this.currVmodel].push(item);
      }
    },
    dataList() {
      var _data = JSON.parse(JSON.stringify(this.dataForm));

      _data.addressField = _data.addressField ? JSON.stringify(_data.addressField) : []

      _data.businessLicense = JSON.stringify(_data.businessLicense);

      return _data;
    },
    dataInfo(dataAll) {
      let _dataAll = dataAll;
      _dataAll.addressField = _dataAll.addressField ? JSON.parse(_dataAll.addressField) : []
      _dataAll.businessLicense = JSON.parse(_dataAll.businessLicense);
      this.dataForm = _dataAll;
    },
    // 获取会员等级列表数据
    getVipGrade(){
      vipLevelList().then(res => {
        if(res.code == 200){
          this.vipLevelIdOptions = res.data.list
        }
      })
    },
    // 行业类别
    industryType(){
        getVipGrade('366943117804306949').then(res => {
            if(res.code == 200){
            this.industryTypeOptions = res.data.list
            }
        })
    },
    // 基地列表
    getBaseManageList(){
      baseManageList().then(res => {
          if(res.code == 200){
            this.baseManageListOptions = res.data.list
          }
        })
    },
    inputChange(){
        this.$forceUpdate()
    },
    // 接口上传成功
    handleSuccess(res, file) {
      if (res.code === 200) {
        this.dataForm.businessLicense = process.env.VUE_APP_BASE_API + res.data.url
      } else {
        this.msgError('上传失败')
      }
    },
    // 上传图片验证
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpg' || file.type === 'image/jpeg' || file.type === 'image/png';
      const isLt5M = file.size / 1024 / 1024 < 5;

      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG/JPEG/PNG 格式!');
      }
      if (!isLt5M) {
        this.$message.error('上传图片大小不能超过 5MB!');
      }
      return isJPG && isLt5M;
    },
    // 上传失败
    handleUploadError() {
      this.$message.error("图片上传失败");
    }
  },
};
</script>
<style scoped>
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
    border: 1px solid #DCDFE6 !important;
    border-radius: 4px !important;
  }
  .avatar{
    width: 100px;
    height: 100px;
  }
</style>
